﻿using System;
using System.Collections.Generic;
using System.Text;

using Warehouse.Common.Entities;
using Warehouse.DataAccess;

namespace Warehouse.BusinessLogic
{
    public class UserBL
    {
        private readonly AbstractProvider _provider = ProviderSettings.DefaultProvider;

        public User Create()
        {
            return _provider.UserDA.Create();
        }

        public int Add(User toUpdate, out int newID)
        {
            if (toUpdate.UserID == 0)
                return _provider.UserDA.Add(toUpdate, out newID);
            else
            {
                newID = toUpdate.UserID;
                return _provider.UserDA.Update(toUpdate);
            }
        }

        public int Update(User toUpdate)
        {
            return _provider.UserDA.Update(toUpdate);
        }

        public int Delete(User toDelete)
        {
            return _provider.UserDA.DeleteByID(toDelete.UserID);
        }

        public User GetByID(int id)
        {
            return _provider.UserDA.GetByID(id);
        }

        public User GetByCode(string code)
        {
            return _provider.UserDA.GetByCode(code);
        }

        public IEnumerable<User> Get(string condition)
        {
            return _provider.UserDA.Get(condition);
        }

        //Other
        public bool Login(string userCode, string passwd)
        {
            var user = _provider.UserDA.GetByCode(userCode);
            return (user != null && user.Passwd.ToUpper() == passwd.ToUpper());
        }

        public bool ChangePasswd(User user, string oldPasswd, string newPasswd)
        {
            if (user.Passwd == oldPasswd)
            {
                user.Passwd = newPasswd;
                return (this.Update(user) > 0);
            }
            return false;
        }
    }
}
